package com.example.mvvmtest.utils;

import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 校验下载文件完整性
 */
public class CheckResUtil {

    private CheckResUtil() {
    }

    public static CheckResUtil getInstance() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static final CheckResUtil instance = new CheckResUtil();
    }

    public boolean checkFile(String filePath,String md5Str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
//            String urlPath = "/zmgame/update/1.3/65217870458162921.apk";
            File file = new File(Environment.getExternalStorageDirectory().getPath() + filePath);
            if (file.exists()) {
                if (file.isFile()){
                    LogUtil.e("是文件");
                }
                else{
                    LogUtil.e("是目录");
                    return false;
                }
            } else {
                LogUtil.e("文件不存在，检查路径是否正确");
                return false;
            }
            FileInputStream inputStream = new FileInputStream(file);
            //对于大文件或者网络文件使用输入流的形式要比字节数组方便很多也节省内存
            DigestInputStream dis = new DigestInputStream(inputStream, digest);
            byte[] buffer = new byte[8986];
            ByteArrayOutputStream fileOutput = new ByteArrayOutputStream();
            //跟读普通输入流是一样的，原理就是需要将输入流读完后，再调用digest方法才能获取整个文件的MD5
            while ((dis.read(buffer)) != -1) {
                fileOutput.write(buffer);
            }
            String fileContent = fileOutput.toString();//读取到的文件的内容
            byte[] summary = digest.digest();
            StringBuffer strBuffer = new StringBuffer();
            for (byte info : summary) {
                String tmp = Integer.toHexString(info & 0xff);
                if (tmp.length() == 1)//如果这个字节的值小于16，那么转换的就只有一个字符，所以需要手动添加一个字符“0”，　　　　
                    tmp = "0" + tmp;
                strBuffer.append(tmp);
            }
//            LogUtil.e(strBuffer.toString());
//            String md5Str = "2F9D747C24B7FAD224FBC782BBB27201";
//            String md5Str1 = "D41D8CD98F00B204E9800998ECF8427E";
            if (strBuffer.toString().equals(md5Str) || strBuffer.toString().equals(md5Str.toLowerCase())) {
                LogUtil.e("文件完整");
                return true;
            } else {
                LogUtil.e("文件不完整");
                return false;
            }
        } catch (NoSuchAlgorithmException | IOException e) {
            LogUtil.e(e.toString());
            e.printStackTrace();
            return false;
        }
    }

}
